<!DOCTYPE html>


<html lang="en">
  

    <head>
      <meta charset="utf-8" />
        
      <meta
        name="viewport"
        content="width=device-width, initial-scale=1, maximum-scale=1"
      />
      <title>《JavaScript高级程序设计》- 第四章：变量、作用域与内存 |  欢迎</title>
  <meta name="generator" content="hexo-theme-ayer">
      
      <link rel="shortcut icon" href="/favicon.ico" />
       
<link rel="stylesheet" href="/dist/main.css">

      <link
        rel="stylesheet"
        href="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/css/remixicon.min.css"
      />
      
<link rel="stylesheet" href="/css/custom.css">
 
      <script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>
       
 

      <link
        rel="stylesheet"
        href="https://cdn.jsdelivr.net/npm/@sweetalert2/theme-bulma@5.0.1/bulma.min.css"
      />
      <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.19/dist/sweetalert2.min.js"></script>

      <!-- mermaid -->
      
      <style>
        .swal2-styled.swal2-confirm {
          font-size: 1.6rem;
        }
      </style>
    <link rel="alternate" href="/atom.xml" title="欢迎" type="application/atom+xml">
</head>
  </html>
</html>


<body>
  <div id="app">
    
      
    <main class="content on">
      <section class="outer">
  <article
  id="post-JavaScript学习/《JavaScript高级程序设计》- 第四章：变量、作用域与内存"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  《JavaScript高级程序设计》- 第四章：变量、作用域与内存
</h1>
 

      
    </header>
     
    <div class="article-meta">
      <a href="/2022/02/12/JavaScript%E5%AD%A6%E4%B9%A0/%E3%80%8AJavaScript%E9%AB%98%E7%BA%A7%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1%E3%80%8B-%20%E7%AC%AC%E5%9B%9B%E7%AB%A0%EF%BC%9A%E5%8F%98%E9%87%8F%E3%80%81%E4%BD%9C%E7%94%A8%E5%9F%9F%E4%B8%8E%E5%86%85%E5%AD%98/" class="article-date">
  <time datetime="2022-02-11T16:07:38.000Z" itemprop="datePublished">2022-02-12</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/JavaScript%E5%AD%A6%E4%B9%A0/">JavaScript学习</a>
  </div>
  
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> Word count:</span>
            <span class="post-count">2.7k</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> Reading time≈</span>
            <span class="post-count">10 min</span>
        </span>
    </span>
</div>
 
    </div>
      
    <div class="tocbot"></div>




  
    <div class="article-entry" itemprop="articleBody">
       
  <h2 id="第四章：变量、作用域与内存"><a href="#第四章：变量、作用域与内存" class="headerlink" title="第四章：变量、作用域与内存"></a>第四章：变量、作用域与内存</h2><h3 id="4-1-原始值与引用值"><a href="#4-1-原始值与引用值" class="headerlink" title="4.1 原始值与引用值"></a>4.1 原始值与引用值</h3><blockquote>
<p>ECMAScript变量包含<code>两种</code>不同类型的数据：<code>原始值</code>和<code>引用值</code>;</p>
</blockquote>
<table>
  <tr>
    <td>分类</td>
    <td>组成</td>
    <td>访问方式</td>
  </tr>
  <tr>
    <td>原始值</td>
    <td>Undefined、Null、Boolean、Number、String和Symbol六种简单数据</td>
    <td>按值访问【操作的就是存储的`实际值`】</td>
  </tr>
  <tr>
    <td>引用值</td>
    <td>由多个值构成的对象</td>
    <td>按引用访问【操作的是该对象的引用，通过引用操作对象】</td>
  </tr>
</table>

<h4 id="4-1-1-动态属性"><a href="#4-1-1-动态属性" class="headerlink" title="4.1.1 动态属性"></a>4.1.1 动态属性</h4><blockquote>
<p>对于<code>原始值</code>而言：不能拥有属性，虽然不会报错，但是无效。</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> person = <span class="string">&#x27;zyzc&#x27;</span>;</span><br><span class="line">person.age = <span class="number">20</span>;</span><br><span class="line"><span class="built_in">console</span>.log(person.age);  <span class="comment">// undefined;</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>对于<code>引用值</code>而言：可以随时添加、修改和删除属性</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> person = <span class="keyword">new</span> <span class="built_in">Object</span>();</span><br><span class="line">person.age = <span class="number">18</span>;</span><br></pre></td></tr></table></figure>

<blockquote>
<p><code>原始值</code>使用<code>new</code>来定义，可以拥有引用值的行为。</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> person = <span class="keyword">new</span> <span class="built_in">String</span>(<span class="string">&#x27;zyzc&#x27;</span>);</span><br><span class="line">person.age = <span class="number">18</span>;</span><br><span class="line"><span class="built_in">console</span>.log(person.age);  <span class="comment">// 18</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="keyword">typeof</span> person); <span class="comment">// Object</span></span><br></pre></td></tr></table></figure>

<h4 id="4-1-2-复制值"><a href="#4-1-2-复制值" class="headerlink" title="4.1.2 复制值"></a>4.1.2 复制值</h4><blockquote>
<p>对于<code>原始值</code>而言:会被复制到<code>新变量的位置</code>。</p>
</blockquote>
<img src='https://pic.imgdb.cn/item/620629352ab3f51d916979e8.png' style='zoom:50%'>

<blockquote>
<p>对于<code>引用值</code>而言：会将引用值从一个变量赋值给另一个变量，然后通过引用共享同一个对象。</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> obj1 = <span class="keyword">new</span> <span class="built_in">Object</span>();</span><br><span class="line">obj1.name = <span class="string">&#x27;zyzc&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> obj2 = obj1;  <span class="comment">// 进行复制</span></span><br><span class="line"><span class="built_in">console</span>.log(obj2.name); <span class="comment">//&#x27;zyzc&#x27;</span></span><br></pre></td></tr></table></figure>
<img src='https://pic.imgdb.cn/item/620630f32ab3f51d917070b9.png' style='zoom:30%'>

<h4 id="4-1-3-传递参数"><a href="#4-1-3-传递参数" class="headerlink" title="4.1.3 传递参数"></a>4.1.3 传递参数</h4><blockquote>
<p>在ECMAScript中，所有函数的传参都是<code>按值传递</code>的。【个人理解为复制副本】</p>
</blockquote>
<blockquote>
<p>对于原始值而言：</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> count = <span class="number">20</span>;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">add</span>(<span class="params">num</span>)</span>&#123;</span><br><span class="line">  num +=<span class="number">10</span>;</span><br><span class="line">  <span class="keyword">return</span> num;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">let</span> result = add(count);</span><br><span class="line"><span class="built_in">console</span>.log(result);    <span class="comment">// 30</span></span><br><span class="line"><span class="built_in">console</span>.log(count);     <span class="comment">// 20;</span></span><br></pre></td></tr></table></figure>

<img src="https://pic.imgdb.cn/item/620633582ab3f51d9172997a.png" style='zoom:50%'>


<blockquote>
<p>对于引用值而言：</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> personA = <span class="keyword">new</span> <span class="built_in">Object</span>();</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">setName</span>(<span class="params">obj</span>)</span>&#123;</span><br><span class="line">  obj.name = <span class="string">&#x27;zyzc&#x27;</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">console</span>.log(personA.name);  <span class="comment">// zyzc</span></span><br></pre></td></tr></table></figure>
<img src="https://pic.imgdb.cn/item/620639a62ab3f51d91788e78.png" style='zoom:50%'>

<blockquote>
<p>难道这个和C++那样，传的是指针吗？</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> personA = <span class="keyword">new</span> <span class="built_in">Object</span>();</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">setName</span>(<span class="params">obj</span>)</span>&#123;</span><br><span class="line">  obj.name = <span class="string">&#x27;zyzc&#x27;</span>;</span><br><span class="line">  obj = <span class="keyword">new</span> <span class="built_in">Object</span>();</span><br><span class="line">  obj.name = <span class="string">&#x27;hi&#x27;</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">console</span>.log(personA.name);  <span class="comment">// zyzc</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>显然，如果是<code>传指针</code>的话，personA的值也会跟着改变为’hi’;</p>
</blockquote>
<h4 id="4-1-4-确定类型"><a href="#4-1-4-确定类型" class="headerlink" title="4.1.4 确定类型"></a>4.1.4 确定类型</h4><blockquote>
<p><code>原始值</code>:使用<code>typeof</code>可以确定类型</p>
</blockquote>
<blockquote>
<p><code>引用值</code>:使用<code>instanceof</code>可以确定是什么类型的对象</p>
</blockquote>
<h3 id="4-2-执行上下文与作用域"><a href="#4-2-执行上下文与作用域" class="headerlink" title="4.2 执行上下文与作用域"></a>4.2 执行上下文与作用域</h3><h4 id="4-2-1-什么是上下文"><a href="#4-2-1-什么是上下文" class="headerlink" title="4.2.1 什么是上下文"></a>4.2.1 什么是上下文</h4><blockquote>
<p><code>上下文</code>决定了<code>可以访问那些数据</code>,<code>可以表现什么行为</code>;而每个上下文都关联着一个<code>变量对象</code>,该<code>变量对象</code>包括了<code>上下文</code>中定义的所有<code>变量</code>和<code>函数</code>;【最外层的上下文是<code>全局上下文</code>，一般指的是<code>window对象</code>】</p>
</blockquote>
<h4 id="4-2-2-上下文怎么工作？"><a href="#4-2-2-上下文怎么工作？" class="headerlink" title="4.2.2 上下文怎么工作？"></a>4.2.2 上下文怎么工作？</h4><blockquote>
<p>每个函数，都有自己的上下文；当代码流入函数的时候，函数的<code>上下文</code>压到<code>上下文栈</code>中，当函数执行完毕之后，函数的<code>上下文</code>会弹出<code>上下文栈</code>。</p>
</blockquote>
<h4 id="4-2-3-什么是作用域链？"><a href="#4-2-3-什么是作用域链？" class="headerlink" title="4.2.3 什么是作用域链？"></a>4.2.3 什么是作用域链？</h4><blockquote>
<p>当<code>上下文</code>代码执行的时候，会创建<code>变量对象</code>的<code>作用域链</code>;该<code>作用域链</code>决定各级上下文访问变量、函数的顺序。当前<code>作用的上下文</code>的<code>变量对象</code>总会在<code>作用域链</code>的<code>最前端</code>。而<code>全局上下文</code>总会在<code>作用域链</code>的<code>最后端</code></p>
</blockquote>
<h4 id="4-2-4-举个例子说明上下文与作用域链"><a href="#4-2-4-举个例子说明上下文与作用域链" class="headerlink" title="4.2.4 举个例子说明上下文与作用域链"></a>4.2.4 举个例子说明上下文与作用域链</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">      这里的上下文：全局上下文</span></span><br><span class="line"><span class="comment">      这里的作用域链：全局变量对象</span></span><br><span class="line"><span class="comment">      这里可以访问的变量：color</span></span><br><span class="line"><span class="comment">      这里可以访问的函数：changeColor</span></span><br><span class="line"><span class="comment">      这里不可以访问的变量：anotherColor、tempColor、anotherColor。因为作用域链上找不到。</span></span><br><span class="line"><span class="comment">  */</span></span><br><span class="line"><span class="keyword">var</span> color = <span class="string">&quot;blue&quot;</span>;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">changeColor</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> anotherColor = <span class="string">&quot;red&quot;</span>;</span><br><span class="line">  <span class="comment">/*</span></span><br><span class="line"><span class="comment">      这里的上下文：anotherColor上下文</span></span><br><span class="line"><span class="comment">      这里的作用域链：changeColor变量对象 ——&gt; 全局变量对象</span></span><br><span class="line"><span class="comment">      这里可以访问的变量：color</span></span><br><span class="line"><span class="comment">      这里可以访问的函数：swapColors</span></span><br><span class="line"><span class="comment">      这里不可以访问的变量：tempColor、anotherColor。因为作用域链上找不到。</span></span><br><span class="line"><span class="comment">  */</span></span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">swapColors</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="comment">/*</span></span><br><span class="line"><span class="comment">      这里的上下文：swapColors上下文</span></span><br><span class="line"><span class="comment">      这里的作用域链：swapColors变量对象 ——&gt; changeColor变量对象 ——&gt; 全局变量对象</span></span><br><span class="line"><span class="comment">      这里可以访问的变量：color、tempColor、anotherColor</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">    <span class="keyword">let</span> tempColor = anotherColor;   <span class="comment">// 当使用到anotherColor变量时，在swapColors变量对象中寻找。若找不到，就顺着作用域链，向后找。直到找到或者未找到为止。</span></span><br><span class="line">    anotherColor = color;</span><br><span class="line">    color = tempColor;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  swapColors();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">changeColor();</span><br></pre></td></tr></table></figure>

<blockquote>
<p><code>寻找变量</code>是顺着<code>作用域链</code>由<code>最前端【自身作用域的变量对象】</code>到<code>最后端【全局作用域的变量对象】</code>、由内层到外层地寻找的。</p>
</blockquote>
<h4 id="4-2-5-作用域链增强"><a href="#4-2-5-作用域链增强" class="headerlink" title="4.2.5 作用域链增强"></a>4.2.5 作用域链增强</h4><blockquote>
<p>某些语句会在作用域链前端<code>临时添加</code>一个上下文.</p>
</blockquote>
<ul>
<li>try/catch中的catch: 会创建一个新的变量对象,其中包含<code>要抛出的错误对象的声明</code></li>
<li>with:会创建一个包含<code>关联对象</code>的变量对象</li>
</ul>
<h3 id="4-3-垃圾回收"><a href="#4-3-垃圾回收" class="headerlink" title="4.3 垃圾回收"></a>4.3 垃圾回收</h3><blockquote>
<p>JavaScript是使用<code>垃圾回收</code>的语言,即由<code>执行环境</code>负责管理内存、内存分配和闲置资源回收.</p>
</blockquote>
<h4 id="4-3-1-垃圾回收基本思路"><a href="#4-3-1-垃圾回收基本思路" class="headerlink" title="4.3.1 垃圾回收基本思路"></a>4.3.1 垃圾回收基本思路</h4><ol>
<li>确定那个变量不会使用</li>
<li>释放其占用的内存</li>
<li>周而复始的执行<blockquote>
<p>显然,<code>确定那个变量不会使用</code>是一个<code>不可判定</code>的问题,所以不能使用算法来解决.只能每隔一段时间,执行一次垃圾回收。</p>
</blockquote>
</li>
</ol>
<h4 id="4-3-2-垃圾回收的策略"><a href="#4-3-2-垃圾回收的策略" class="headerlink" title="4.3.2 垃圾回收的策略"></a>4.3.2 垃圾回收的策略</h4><ul>
<li><p>标记清理:当进行垃圾回收的时候,通过变量的标记,来判定是否需要销毁并回收内存.标记的方法有很多:</p>
<ol>
<li>当变量进入上下文的时候,反转某一位;然后离开上下文的时候,再进行反转.从而达到标记的效果。</li>
<li>维护两个表:在上下文表、不在上下文表;</li>
</ol>
</li>
<li><p>引用计数:声明变量并赋值的时候,值的引用数为1;如果同一个值又被赋给另外一个变量,则<code>引用数+1</code>;若保存对该值的引用的变量被其他值覆盖,则<code>引用数-1</code>;当运行垃圾回收程序的时候,会将<code>引用数为0的值清理</code>。</p>
</li>
</ul>
<blockquote>
<p>现在的浏览器采用的大多是<code>标记清理</code>,因为引用计数存在<code>循环引用</code>问题:</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">bugTest</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">  <span class="keyword">let</span> objectA = <span class="keyword">new</span> <span class="built_in">Object</span>();</span><br><span class="line">  <span class="keyword">let</span> objectB = <span class="keyword">new</span> <span class="built_in">Object</span>();</span><br><span class="line"></span><br><span class="line">  objectA.tail = objectB;</span><br><span class="line">  objectB.head = objectA;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>虽然说两者相互引用确实不应该被清除,但是一旦代码<code>不在bugTest的上下文中</code>后,这两个对象还是会一直存在,不被清理。</p>
</blockquote>
<h3 id="4-4-性能与内存管理"><a href="#4-4-性能与内存管理" class="headerlink" title="4.4 性能与内存管理"></a>4.4 性能与内存管理</h3><h4 id="4-4-1-什么会影响性能"><a href="#4-4-1-什么会影响性能" class="headerlink" title="4.4.1 什么会影响性能?"></a>4.4.1 什么会影响性能?</h4><ul>
<li>如果内存中分配了很多变量,则可能会造成性能的损失。</li>
<li>如果垃圾回收程序的执行时间太长,也可能会造成性能的损失。</li>
</ul>
<h4 id="4-4-2-内存管理"><a href="#4-4-2-内存管理" class="headerlink" title="4.4.2 内存管理"></a>4.4.2 内存管理</h4><blockquote>
<p>在JavaScript中,因为具有垃圾回收机制,所以开发者通常无需关心内存管理。</p>
</blockquote>
<ol>
<li><p>如果需要优化内存占用,最佳的手段就是:保证在执行代码的时候,只保存<code>有必要的数据</code>。如果数据不再必要,可以通过将其<code>设置为null</code>,从而<code>释放引用</code>,这也叫做<code>解除引用</code>。</p>
</li>
<li><p>通过const和let声明提升性能：这两个关键字声明的变量，可能让垃圾回收程序尽早介入，并尽早释放并回收内存。</p>
</li>
<li><p>隐藏类和删除操作：V8引擎，为了追踪对象的属性特征，会创建<code>隐藏类</code>并与<code>对象</code>关联起来。其中，<code>隐藏类会占用空间</code>;</p>
 <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Animal</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">  <span class="built_in">this</span>.name = <span class="string">&#x27;dog&#x27;</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// dog1 和 dog2 共享一个隐藏类</span></span><br><span class="line"><span class="keyword">let</span> dog1 = <span class="keyword">new</span> Animal();</span><br><span class="line"><span class="keyword">let</span> dog2 = <span class="keyword">new</span> Animal();  </span><br><span class="line">    </span><br><span class="line"><span class="comment">// 但是进行属性添加后，</span></span><br><span class="line">dog2.sex = <span class="string">&#x27;male&#x27;</span>; <span class="comment">// dog1 和 dog2 关联的隐藏类就不一样了。从而增加了内存占用</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>为了避免以上<code>先创建再补充</code>而导致的问题，应当在<code>构造函数</code>中<code>一次性声明</code>所需属性；</p>
 <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Animal</span>(<span class="params">sex</span>)</span>&#123;</span><br><span class="line">  <span class="built_in">this</span>.name = <span class="string">&#x27;dog&#x27;</span>;</span><br><span class="line">  <span class="built_in">this</span>.sex = sex;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// dog1 和 dog2 共享一个隐藏类</span></span><br><span class="line"><span class="keyword">let</span> dog1 = <span class="keyword">new</span> Animal();</span><br><span class="line"><span class="keyword">let</span> dog2 = <span class="keyword">new</span> Animal(<span class="string">&quot;male&quot;</span>); </span><br><span class="line">    </span><br><span class="line"><span class="comment">// 当不需要该对象的时候，应该这样操作</span></span><br><span class="line">dog2 = <span class="literal">null</span>;  <span class="comment">// 解除引用</span></span><br></pre></td></tr></table></figure></blockquote>
</li>
<li><p>对象池与静态分配 </p>
<blockquote>
<p>为了提升JavaScript的性能，最后只能<code>压榨</code>浏览器了。此中的关键就是：<code>减少浏览器执行垃圾回收的次数</code>，从而保住因释放内存而损失的性能。</p>
</blockquote>
<blockquote>
<p>决定浏览器什么时候运行垃圾回收程序的一个标准就是：<code>对象的更替速度</code>，如果很<code>多对象被初始化</code>、又一下子<code>超出作用域</code>，则会调度垃圾回收程序。</p>
</blockquote>
<blockquote>
<p>优化前：每次调用这个函数，都会创建一个新的Vector，若多次调用，则会导致对象的更替速度变快。</p>
 <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">addVector</span>(<span class="params">a,b</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> resultant = <span class="keyword">new</span> Vector();</span><br><span class="line">  resultant.x = a.x + b.x;</span><br><span class="line">  resultant.y = a.y + b.y;</span><br><span class="line">  <span class="keyword">return</span> resultant;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>优化后：当多次调用的时候，由于<code>没有发生对象的初始化</code>，垃圾回收探测就不会发现有<code>对象更替</code>。</p>
 <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">addVector</span>(<span class="params">a,b,resultant</span>) </span>&#123;</span><br><span class="line">  resultant.x = a.x + b.x;</span><br><span class="line">  resultant.y = a.y + b.y;</span><br><span class="line">  <span class="keyword">return</span> resultant;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 创建一个对象池，用来管理可回收的对象。</span></span><br><span class="line"><span class="keyword">const</span> vectorPool = &#123;</span><br><span class="line">  <span class="attr">v1</span>:<span class="keyword">new</span> <span class="built_in">Object</span>(),</span><br><span class="line">  <span class="attr">v2</span>:<span class="keyword">new</span> <span class="built_in">Object</span>(),</span><br><span class="line">  <span class="attr">v3</span>:<span class="keyword">new</span> <span class="built_in">Object</span>()</span><br><span class="line">&#125;;</span><br><span class="line">    </span><br><span class="line">vectorPool.v1.x = <span class="number">10</span>;</span><br><span class="line">vectorPool.v1.y = <span class="number">5</span>;</span><br><span class="line">    </span><br><span class="line">vectorPool.v2.x = <span class="number">10</span>;</span><br><span class="line">vectorPool.v2.y = <span class="number">5</span>;</span><br><span class="line">    </span><br><span class="line">addVector(vectorPool.v1,vectorPool.v2,vectorPool.v3);</span><br><span class="line">    </span><br><span class="line"><span class="built_in">console</span>.log(vectorPool.v3.x + <span class="string">&#x27;&#x27;</span> + vectorPool.v3.y);  <span class="comment">// 20 10</span></span><br><span class="line">    </span><br><span class="line"><span class="comment">// 解除引用</span></span><br><span class="line">v1 = <span class="literal">null</span>;</span><br><span class="line">v2 = <span class="literal">null</span>;</span><br><span class="line">v3 = <span class="literal">null</span>;</span><br></pre></td></tr></table></figure>
<p>除了使用对象池，也可以使用<code>数组</code>进行静态分配。</p>
</blockquote>
</li>
</ol>
<blockquote>
<p>但是数组的大小是<code>动态可变</code>的,为了避免数组大小变化的时候，引来垃圾回收；所以要一开始就预定好<code>够用的数组</code>;</p>
</blockquote>
<h3 id="4-5-总结："><a href="#4-5-总结：" class="headerlink" title="4.5 总结："></a>4.5 总结：</h3><ol>
<li><code>原始值</code>和<code>引用值</code>有如下特点：</li>
</ol>
<ul>
<li>原始值，大小固定，存储在<code>栈内存</code>上。</li>
<li>引用值是对象，存储在<code>堆内存</code>上。</li>
<li>包含引用值得变量，实际是一个<code>指向对象的指针</code>。</li>
<li>引用值的复制，就是<code>指针的复制</code>。</li>
<li><code>typeof</code>确定原始类型；<code>instanceof</code>确定引用类型。</li>
</ul>
<ol start="2">
<li>关于<code>上下文（作用域）</code></li>
</ol>
<ul>
<li>上下文<code>决定</code>了<code>变量的生命周期</code></li>
<li>执行上下文分为：<code>全局上下文</code>、<code>函数上下文</code>和<code>块级上下文</code></li>
<li>代码流入一个<code>新上下文</code>，都会创建一个作用域链，用于搜索变量和函数</li>
<li>作用域的搜索，是自内层到外层的，所以全局作用域只能访问全局上下文的变量和函数。</li>
<li>变量的执行上下文，用于确定什么时候释放内存。</li>
</ul>
<ol start="3">
<li>关于垃圾回收程序</li>
</ol>
<ul>
<li>离开作用域的值，会被标记为<code>可回收</code>，等待垃圾回收程序执行期间被删除。</li>
<li>主流的垃圾回收是<code>标记清理</code></li>
<li>某些旧版本IE仍会使用<code>引用计数</code></li>
<li><code>解除变量</code>是一个很好的习惯。既可以消除<code>循环引用</code>，也可以帮助垃圾回收。</li>
</ul>
 
      <!-- reward -->
      
    </div>
    

    <!-- copyright -->
    
    <div class="declare">
      <ul class="post-copyright">
        <li>
          <i class="ri-copyright-line"></i>
          <strong>Copyright： </strong>
          
          Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
          
        </li>
      </ul>
    </div>
    
    <footer class="article-footer">
       
<div class="share-btn">
      <span class="share-sns share-outer">
        <i class="ri-share-forward-line"></i>
        分享
      </span>
      <div class="share-wrap">
        <i class="arrow"></i>
        <div class="share-icons">
          
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="ri-weibo-fill"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="ri-wechat-fill"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="ri-qq-fill"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="ri-douban-line"></i>
          </a>
          <!-- <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a> -->
          
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="ri-facebook-circle-fill"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="ri-twitter-fill"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="ri-google-fill"></i>
          </a>
        </div>
      </div>
</div>

<div class="wx-share-modal">
    <a class="modal-close" href="javascript:;"><i class="ri-close-circle-line"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="//api.qrserver.com/v1/create-qr-code/?size=150x150&data=http://example.com/2022/02/12/JavaScript%E5%AD%A6%E4%B9%A0/%E3%80%8AJavaScript%E9%AB%98%E7%BA%A7%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1%E3%80%8B-%20%E7%AC%AC%E5%9B%9B%E7%AB%A0%EF%BC%9A%E5%8F%98%E9%87%8F%E3%80%81%E4%BD%9C%E7%94%A8%E5%9F%9F%E4%B8%8E%E5%86%85%E5%AD%98/" alt="微信分享二维码">
    </div>
</div>

<div id="share-mask"></div>  
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/JavaScript/" rel="tag">JavaScript</a></li></ul>

    </footer>
  </div>

   
  <nav class="article-nav">
    
      <a href="/2022/02/13/JavaScript%E5%AD%A6%E4%B9%A0/%E3%80%8AJavaScript%E9%AB%98%E7%BA%A7%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1%E3%80%8B-%20%E7%AC%AC%E4%BA%94%E7%AB%A0%EF%BC%9A%E5%9F%BA%E6%9C%AC%E5%BC%95%E7%94%A8%E7%B1%BB%E5%9E%8B/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            《JavaScript高级程序设计》- 第五章：基本引用类型
          
        </div>
      </a>
    
    
      <a href="/2022/02/11/JavaScript%E5%AD%A6%E4%B9%A0/%E3%80%8AJavaScript%E9%AB%98%E7%BA%A7%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1%E3%80%8B-%20%E7%AC%AC%E4%B8%89%E7%AB%A0%EF%BC%9A%E8%AF%AD%E8%A8%80%E5%9F%BA%E7%A1%80/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">《JavaScript高级程序设计》- 第三章：语言基础</div>
      </a>
    
  </nav>

   
<!-- valine评论 -->
<div id="vcomments-box">
  <div id="vcomments"></div>
</div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine@1.4.14/dist/Valine.min.js"></script>
<script>
  new Valine({
    el: "#vcomments",
    app_id: "jeb2pvxjdeJQOj5OG3AUavGv-gzGzoHsz",
    app_key: "6YlB9tQJTstHMM8GOwFu4uyY",
    path: window.location.pathname,
    avatar: "monsterid",
    placeholder: "给我的文章加点评论吧~",
    recordIP: true,
  });
  const infoEle = document.querySelector("#vcomments .info");
  if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0) {
    infoEle.childNodes.forEach(function (item) {
      item.parentNode.removeChild(item);
    });
  }
</script>
<style>
  #vcomments-box {
    padding: 5px 30px;
  }

  @media screen and (max-width: 800px) {
    #vcomments-box {
      padding: 5px 0px;
    }
  }

  #vcomments-box #vcomments {
    background-color: #fff;
  }

  .v .vlist .vcard .vh {
    padding-right: 20px;
  }

  .v .vlist .vcard {
    padding-left: 10px;
  }
</style>

 
   
     
</article>

</section>
      <footer class="footer">
  <div class="outer">
    <ul>
      <li>
        Copyrights &copy;
        2022
        <i class="ri-heart-fill heart_icon"></i> 子与子乘
      </li>
    </ul>
    <ul>
      <li>
        
      </li>
    </ul>
    <ul>
      <li>
        
        
        <span>
  <span><i class="ri-user-3-fill"></i>Visitors:<span id="busuanzi_value_site_uv"></span></span>
  <span class="division">|</span>
  <span><i class="ri-eye-fill"></i>Views:<span id="busuanzi_value_page_pv"></span></span>
</span>
        
      </li>
    </ul>
    <ul>
      
    </ul>
    <ul>
      
    </ul>
    <ul>
      <li>
        <!-- cnzz统计 -->
        
      </li>
    </ul>
  </div>
</footer>    
    </main>
    <div class="float_btns">
      <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>

<div class="todark" id="todark">
  <i class="ri-moon-line"></i>
</div>

    </div>
    <aside class="sidebar on">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/ayer-side.svg" alt="欢迎"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">归档</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/friends">友链</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="Search">
        <i class="ri-search-line"></i>
      </a>
      
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i></p>
  <div class="reward-box">
    
    
  </div>
</div>
    
<script src="/js/jquery-3.6.0.min.js"></script>
 
<script src="/js/lazyload.min.js"></script>

<!-- Tocbot -->
 
<script src="/js/tocbot.min.js"></script>

<script>
  tocbot.init({
    tocSelector: ".tocbot",
    contentSelector: ".article-entry",
    headingSelector: "h1, h2, h3, h4, h5, h6",
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer: "main",
    positionFixedSelector: ".tocbot",
    positionFixedClass: "is-position-fixed",
    fixedSidebarOffset: "auto",
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link
  rel="stylesheet"
  href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css"
/>
<script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/js/jquery.justifiedGallery.min.js"></script>

<script src="/dist/main.js"></script>

<!-- ImageViewer -->
 <!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.min.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script> 
<!-- MathJax -->

<!-- Katex -->

<!-- busuanzi  -->
 
<script src="/js/busuanzi-2.3.pure.min.js"></script>
 
<!-- ClickLove -->

<!-- ClickBoom1 -->

<!-- ClickBoom2 -->

<!-- CodeCopy -->
 
<link rel="stylesheet" href="/css/clipboard.css">
 <script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
  function wait(callback, seconds) {
    var timelag = null;
    timelag = window.setTimeout(callback, seconds);
  }
  !function (e, t, a) {
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '<i class="ri-file-copy-2-line"></i><span>COPY</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      $(".article pre code").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });
      clipboard.on('success', function(e) {
        let $btn = $(e.trigger);
        $btn.addClass('copied');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-checkbox-circle-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPIED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-checkbox-circle-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
      clipboard.on('error', function(e) {
        e.clearSelection();
        let $btn = $(e.trigger);
        $btn.addClass('copy-failed');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-time-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPY FAILED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-time-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
    }
    initCopyCode();
  }(window, document);
</script>
 
<!-- CanvasBackground -->

<script>
  if (window.mermaid) {
    mermaid.initialize({ theme: "forest" });
  }
</script>


    
    

  </div>
</body>

</html>